using Admin2025.Domain.Events;

namespace Admin2025.Domain.Entities.App;

public class AppUser : EntityBase
{
    public string Username { get; set; } = null!;
    public string Password { get; set; } = null!;
    public string Salt { get; set; } = null!;

    public string? AvatarUrl { get; set; }
    public string? Nickname { get; set; }
    public Guid? DepartmentId { get; set; }
    public AppDepartment? Department { get; set; }

    public ICollection<AppRole> Roles { get; set; } = new List<AppRole>();

    /// <summary>
    /// 创建新用户（静态工厂方法）
    /// </summary>
    public static AppUser Create(string username, string password, string salt, string? nickname = null, Guid? departmentId = null)
    {
        var user = new AppUser
        {
            Id = Guid.NewGuid(),
            Username = username,
            Password = password,
            Salt = salt,
            Nickname = nickname,
            DepartmentId = departmentId,
            CreatedAt = DateTime.UtcNow,
            UpdatedAt = DateTime.UtcNow
        };

        // 发布用户创建事件
        user.AddDomainEvent(new UserCreatedEvent(user.Id, user.Username, user.Nickname, user.DepartmentId));

        return user;
    }

    public void AssignRole(AppRole role)
    {
        if (!Roles.Contains(role))
            Roles.Add(role);
    }
    public void RemoveRole(AppRole role)
    {
        if (Roles.Contains(role))
            Roles.Remove(role);
    }
    public void ChangePassword(string oldPwdHash, string newPwdHash)
    {
        if (Password != oldPwdHash) throw new Exception("原密码错误");
        Password = newPwdHash;
    }
    public void UpdateNickname(string nickname) => Nickname = nickname;
    public void UpdateAvatar(string avatarUrl) => AvatarUrl = avatarUrl;
    public void Enable() => IsActived = true;
    public void Disable() => IsActived = false;

    /// <summary>
    /// 软删除用户
    /// </summary>
    public void SoftDelete(Guid deletedBy)
    {
        IsDeleted = true;
        UpdatedAt = DateTime.UtcNow;
        UpdatedBy = deletedBy;

        // 发布用户删除事件
        AddDomainEvent(new UserDeletedEvent(Id, Username, deletedBy));
    }
}